package com.example.role.auth;

import com.example.role.pojo.User;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.joda.time.DateTime;

/**
 * @BelongsProject: jw
 * @BelongsPackage: com.wn.auth
 * @Author: tkrestnhmt
 * @CreateTime: 2020-07-08 10:52
 * @Description:
 */
public class JWTUtil {

    /**
     * 生成token,使用私钥对数据进行加密生成jwt
     * @param user：荷载
     * @param date：过期时间，单位分钟
     * @param priRsaPath：私钥的路径
     * @return
     *
     *
     * claim():荷载
     * DateTime.now().plusMinutes(30).toDate():过期时间，单位分钟
     *
     * SignatureAlgorithm.RS256:表示加密算法是rsa256
     * RsaUtils.getPrivateKey("E:\\\\rsa\\\\pri.rsa")：用来加密的私钥
     */
    public static String generateToken(User user, Integer date, String priRsaPath){
        String token = null;
        try {
            token = Jwts.builder().claim("id", user.getUserId())
                    .claim("username", user.getUserAccount())
                    .claim("role", user.getRole())
                    .setExpiration(DateTime.now().plusMinutes(date).toDate())
                    .signWith(SignatureAlgorithm.RS256, RsaUtils.getPrivateKey(priRsaPath))
                    .compact();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return token;
    }

    /**
     * 解析token
     * @param token：要解析的token字符串
     * @param ：公钥路径
     * @return
     * setSigningKey(RsaUtils.getPublicKey("E:\\rsa\\pub.rsa"))：解密的公钥路径
     * parseClaimsJws(token)：指定要解密的token字符串
     * getBody()取出token中的荷载
     */
    public static User parserToken(String token,String pubRsapath){
        User user = null;
        try {
            Claims body = Jwts.parser().setSigningKey(RsaUtils.getPublicKey(pubRsapath))
                    .parseClaimsJws(token)
                    .getBody();
            Integer id = (Integer) body.get("id");
            String username = (String) body.get("username");
            Integer role = (Integer) body.get("role");
            user = new User();
            user.setUserId(id);
            user.setUserAccount(username);
            user.setRole(role);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return user;
    }
}
